//@author A0100704B
//This class support functionalities for searching tasks
package crossoff.logic;

import java.io.IOException;
import java.util.ArrayList;

import crossoff.db.Storage;
import crossoff.model.GUIobject;
import crossoff.model.Task;

public class CommandSearchTask {

	private static final String SEARCH_MESSAGE_PREFIX = "SEARCH FOR ";
	private static final String SEARCH_MODE = "SEARCH";

	public static GUIobject searchTask(String command) throws IOException {
		ArrayList<Task> searchCache = new ArrayList<Task>();
		command = command.replaceFirst("search ", "");

		for (Task task : Storage.getInstance().taskCache) {
			if (taskContainsSearchString(command, task)){
				searchCache.add(task);
			}
			else{
				continue;
			}
		}
		if(searchCache.isEmpty()){
			return new GUIobject(searchCache, "NO MATCHES FOUND", "", SEARCH_MODE);
		}
		return new GUIobject(searchCache, SEARCH_MESSAGE_PREFIX + command.toUpperCase(), "", SEARCH_MODE);
	}

	private static boolean taskContainsSearchString(String command, Task task)
			throws IOException {
		return Storage.getInstance().getEditDescription(task.getTaskID()).toLowerCase()
				.contains(command.toLowerCase());
	}
}
